package com.roc.web.action.settlemgr;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.roc.bean.ApplyChannel;
import com.roc.newPage.IPageService;
import com.roc.page.BaseSearchCondition;
import com.roc.page.PaginationBaseAction;
import com.roc.pojo.Operators;
import com.roc.pojo.TblSettleItem;
import com.roc.service.IApplyMoneyService;
import com.roc.service.IExcelService;
import com.roc.service.IPagenitionService;
import com.roc.util.Constance;
import com.roc.util.constant.Constant;
import com.roc.util.constant.Role;
@Component
@Scope("prototype")
@Namespace("/temp")
public class TempChannelAction extends PaginationBaseAction{
	private static final long serialVersionUID = 1L;
	private SettlementApplyMoneySearchCondition searchCondition;
	private static Logger logger = LogManager.getLogger(TempChannelAction.class);
	private String[] multiSel;
	private InputStream excelFile;
	private List<ApplyChannel> channelList;
	/*@Autowired
	private IPageService pagenitionService;*/
	@Autowired
	private IPagenitionService pagenitionService;
	@Autowired
	private IApplyMoneyService applyService;
	@Autowired
	private IExcelService excelService;
	/**
	 * 初始化待出款页面
	 * @return
	 */
	@Action(value="initJsp",results={@Result(name="success",location="/pages/settlementMoney/tempChannelList.jsp"),
			@Result(name = "error", location = "/error.jsp")})
	public String queryMakeMoneyJsp(){
		Operators op = (Operators) getSession().getAttribute(
			Constant.SESSION_LOGIN_MERCHANT);
		if (op.getRoleType().equals(Role.CLEAR_OPERATORS.getCode())
			|| op.getRoleType().equals(Role.CLEAR_LEAD.getCode())
			|| op.getRoleType().equals(Role.SYSTEM.getCode())) {
			searchCondition=new SettlementApplyMoneySearchCondition();
			String today = Constance.currTime();
			searchCondition.setApplyDateMin(today);
			searchCondition.setApplyDateMax(today);
			return SUCCESS;
		}
		addActionError("无权限访问!!!");
		return ERROR;		
	}
	/**
	 * 待出款列表
	 * @return
	 */
	@Action(value="queryChannelJsp",results={@Result(name="success",location="/pages/settlementMoney/tempChannelList.jsp")})
	public String querySettlementMsgList(){
		try {
			Operators op = (Operators) getSession().getAttribute(
					Constant.SESSION_LOGIN_MERCHANT);
			if (op.getRoleType().equals(Role.CLEAR_OPERATORS.getCode())
					|| op.getRoleType().equals(Role.CLEAR_LEAD.getCode())
					|| op.getRoleType().equals(Role.SYSTEM.getCode())) {
				if(searchCondition == null){
					searchCondition = (SettlementApplyMoneySearchCondition) getSearchConditionFromSession();
					if(searchCondition == null){
						searchCondition = new SettlementApplyMoneySearchCondition();
					}
				}
				String message=null;
				Map<String,Object> resultMap=null;
				//首先处理拼凑问题
				if(Constance.isNotEmpty(searchCondition.getAmtMax()) && "retry".equals(searchCondition.getCombineFlag())){//条件存在并且拼凑
					Operators o=new Operators();
					o.setAccountNo(op.getAccountNo()+"temp");
					applyService.clearOriginCombie(searchCondition,o);
					resultMap=applyService.handleCombineAmt(searchCondition,o);
					if(resultMap.containsKey("result")){
							message=resultMap.get("result").toString();
							searchCondition.setCombingName(o.getAccountNo());//设置标记
							searchCondition.setCombineFlag("exists");
						}					
				}					
			
			int rows=pagenitionService.countSQL(searchCondition);
			if(rows>0){
				searchRsList=pagenitionService.findAllSQL(searchCondition, calcuStart(getCurrentPage()), Constance.PAGE_MAX_SIZE);
			}
			
			List<TblSettleItem> settleList = new ArrayList<TblSettleItem>();
			double amt=0,part=0;
			dealTheSearchRsList(searchRsList,settleList);
			if(message==null){
				DecimalFormat df=new DecimalFormat("0.00");
				message="已统计出记录"+rows+"条，";
				if(Constance.isNotEmpty(searchCondition.getAmtMax())){
					List<Object> other=pagenitionService.findAllSQL(searchCondition,0,rows);
					for(Object object:other){//拼凑的总金额
						Object[] o=(Object[]) object;
						part=part+Double.valueOf(Constance.Null2EmptyTrim(o[20]));
					}
					message=message+"拼凑总金额:"+df.format(part)+"元，";	
				}
				for(TblSettleItem item:settleList){//筛选的当前页面总金额
					amt=amt+item.getUnFreezeAmt();
				}				
				message=message+"当前页面累计金额:"+df.format(amt)+"元";	
			}
			addActionMessage(message);			
			getRequest().setAttribute("settleList", settleList);
			this.setTotalPage(this.calcuTotalPage(rows));
			getRequest().setAttribute(CURRENT_PAGE, this.getCurrentPage());
			getRequest().setAttribute(TOTAOL_PAGE, this.getTotalPage());
			setSearchToConditionSession(searchCondition);			
			return SUCCESS;
			}
			addActionError("无权限访问!!!");
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
			addActionError("待出款查询异常");
			return ERROR;
		}
		return ERROR;
	}
	
	/**
	 * 选择导出(复选框模式)
	 * @return
	 */
	@Action(value = "selectExportInit", results = {
			@Result(name = "success", type = "stream", params = {
					"contentType", "application/vnd.ms-excel", "inputName",
					"excelFile", "contentDisposition",
					"attachment;filename=${excelName}.xlsx", "bufferSize",
					"1024*3" }),
			@Result(name = "error", location = "/error.jsp") })
	public String applyMoneyListSimple(){
		try {
			Operators op = (Operators) getSession().getAttribute(
					Constant.SESSION_LOGIN_MERCHANT);
			if (op.getRoleType().equals(Role.CLEAR_OPERATORS.getCode())
					|| op.getRoleType().equals(Role.CLEAR_LEAD.getCode())
					|| op.getRoleType().equals(Role.SYSTEM.getCode())) {				
				List<TblSettleItem> settlelList=applyService.selectBySerialNo(multiSel);
				logger.info("开始导出汇出信息~");
				SXSSFWorkbook work = excelService.exportTempList(settlelList);	
				ByteArrayOutputStream output = new ByteArrayOutputStream();
				work.write(output);	
				byte[] ba = output.toByteArray();
				excelFile = new ByteArrayInputStream(ba);
				output.flush();
				output.close();
				applyService.selectExportUpdate(searchCondition,multiSel,op);
				logger.info("导出汇出信息成功~");
				return SUCCESS;
			}
			addActionError("无权限访问!!!");
		} catch (Exception e) {
			logger.error("导出部分汇出异常",e);
			addActionMessage("导出部分汇出异常");
			return ERROR;
		}
		return ERROR;
	}
	/**
	 * 批量导出
	 * @return
	 */
	@Action(value = "batchExportInit", results = {
			@Result(name = "success", type = "stream", params = {
					"contentType", "application/vnd.ms-excel", "inputName",
					"excelFile", "contentDisposition",
					"attachment;filename=${excelName}.xlsx", "bufferSize",
					"1024*3" }),
			@Result(name = "error", location = "/error.jsp") })
	public String applyMoneyList(){

		try {
			Operators op = (Operators) getSession().getAttribute(
					Constant.SESSION_LOGIN_MERCHANT);
			if (op.getRoleType().equals(Role.CLEAR_OPERATORS.getCode())
					|| op.getRoleType().equals(Role.CLEAR_LEAD.getCode())) {
				if(searchCondition == null){
					searchCondition = (SettlementApplyMoneySearchCondition) getSearchConditionFromSession();
					if(searchCondition == null){
						searchCondition = new SettlementApplyMoneySearchCondition();
					}
				}
				int rows=pagenitionService.countSQL(searchCondition);
				if(rows>0){
					searchRsList=pagenitionService.findAllSQL(searchCondition,0,rows);
				}
				
				List<TblSettleItem> settleList = new ArrayList<TblSettleItem>();
				dealTheSearchRsList(searchRsList,settleList);				
				logger.info("开始导出汇出信息~");
				SXSSFWorkbook work = excelService.exportTempList(settleList);
	
				ByteArrayOutputStream output = new ByteArrayOutputStream();
				work.write(output);
	
				byte[] ba = output.toByteArray();
				excelFile = new ByteArrayInputStream(ba);
				output.flush();
				output.close();
				applyService.batchExportUpdate(searchCondition, op);
				logger.info("导出汇出信息成功~");	
				return SUCCESS;
			}
			addActionError("无权限访问!!!");
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			addActionError(e.getMessage());
			return ERROR;
		}
		return ERROR;
	}
	
	private void dealTheSearchRsList(List<Object> searchRsList,
			List<TblSettleItem> settleList) throws Exception {
		try {
			if(searchRsList != null && searchRsList.size() > 0){
				Iterator<Object> it = searchRsList.iterator();
				while(it.hasNext()){
					Object[] obj = (Object[]) it.next();
					TblSettleItem bean = new TblSettleItem();
					bean.setId(Long.parseLong(Constance.Null2EmptyTrim(obj[0])));
					bean.setInsIdCd(Constance.Null2EmptyTrim(obj[1]));
					bean.setMchtCd(Constance.Null2EmptyTrim(obj[2]));
					bean.setMchtName(Constance.Null2EmptyTrim(obj[3]));
					String transAmt = Constance.Null2EmptyTrim(obj[4]);
					if(!"".equals(transAmt)){
						bean.setTransAmt(Double.parseDouble(transAmt));
					}else{
						bean.setTransAmt(0.00);
					}
					String totalNum = Constance.Null2EmptyTrim(obj[5]); 
					if(!"".equals(totalNum)){
						bean.setTotalNum(Integer.parseInt(totalNum));
					}else{
						bean.setTotalNum(0);
					}
					String mchtFee = Constance.Null2EmptyTrim(obj[6]);
					if(!"".equals(mchtFee)){
						bean.setMchtFee(Double.parseDouble(mchtFee));
					}else{
						bean.setMchtFee(0.00);
					}
					String setAmt = Constance.Null2EmptyTrim(obj[7]);
					if(!"".equals(setAmt)){
						bean.setMchtSetAmt(Double.parseDouble(setAmt));
					}else{
						bean.setMchtSetAmt(0.00);
					}
					bean.setBankName(Constance.Null2EmptyTrim(obj[8]));
					bean.setBankCode(Constance.Null2EmptyTrim(obj[9]));
					bean.setAccount(Constance.Null2EmptyTrim(obj[10]));
					bean.setAccountName(Constance.Null2EmptyTrim(obj[11]));
					bean.setAccType(Constance.Null2EmptyTrim(obj[12]));
					bean.setSettleDate(Constance.Null2EmptyTrim(obj[13]));
					bean.setSettleFlag(Constance.Null2EmptyTrim(obj[14]));
					bean.setSetDate(Constance.Null2EmptyTrim(obj[15]));
					bean.setFreezeFlag(Constance.Null2EmptyTrim(obj[16]));
					String freezeAmt = Constance.Null2EmptyTrim(obj[19]);
					if(!"".equals(freezeAmt)){
						bean.setFreezeAmt(Double.parseDouble(freezeAmt));
					}else{
						bean.setFreezeAmt(0.00);
					}
					String unfreezeAmt = Constance.Null2EmptyTrim(obj[20]);
					if(!"".equals(unfreezeAmt)){
						bean.setUnFreezeAmt(Double.parseDouble(unfreezeAmt));;
					}else{
						bean.setUnFreezeAmt(0.00);
					}
					bean.setRemark1(Constance.Null2EmptyTrim(obj[21]));
					bean.setRemark(Constance.Null2EmptyTrim(obj[22]));
					settleList.add(bean);					
				}
			}
		}catch (Exception e) {
			throw new Exception("解析数据封装到待出款信息实体类异常");
		}
	}	
	@Override
	protected BaseSearchCondition getSearchConditionFromSubClass()
			throws Exception {
		return searchCondition;
	}

	@Override
	protected void setSearchConditionToSubClass(
			BaseSearchCondition searchCondition) throws Exception {
		this.setSearchConditionToSubClass(searchCondition);
	}

	@Override
	protected void setSearchToConditionSession(
			BaseSearchCondition searchCondition) {
		getSession().setAttribute(SEARCH_SESSION_TEMP_MONEY_QUERY, searchCondition);
	}

	@Override
	protected BaseSearchCondition getSearchConditionFromSession() {
		return (SettlementApplyMoneySearchCondition)getSession().getAttribute(SEARCH_SESSION_TEMP_MONEY_QUERY);
	}

	@Override
	protected String getInitPageSize() {
		return Constance.PAGE_MAX_SIZE+"";
	}

	public SettlementApplyMoneySearchCondition getSearchCondition() {
		return searchCondition;
	}

	public void setSearchCondition(
			SettlementApplyMoneySearchCondition searchCondition) {
		this.searchCondition = searchCondition;
	}
	
	public String[] getMultiSel() {
		return multiSel;
	}
	public void setMultiSel(String[] multiSel) {
		this.multiSel = multiSel;
	}
	
	
	public List<ApplyChannel> getChannelList() {
		return channelList;
	}
	public void setChannelList(List<ApplyChannel> channelList) {
		this.channelList = channelList;
	}
	public InputStream getExcelFile() {
		return excelFile;
	}
	public void setExcelFile(InputStream excelFile) {
		this.excelFile = excelFile;
	}
	public String getExcelName() {
		String excelName = "上海银行对公明细报表" + Constance.formateDate();

		try {
			excelName = new String(excelName.getBytes(), "ISO8859-1");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			logger.info("生成excel名称失败了！");
		}

		return excelName;
	}
}
